<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class GoodsSpu extends Model
{
    use SoftDeletes;

    const CREATED_AT = 'createtime';
    const UPDATED_AT = 'updatetime';
    const DELETED_AT = 'deletetime';

    //表名
    protected $table = 'goods_spu';

    //批量赋值
    protected $fillable = ['status', 'deletetime'];

    // 追加属性
    protected $appends = [
        'spec_type_text',
        'status_text'
    ];

    public function getSupplyPriceAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    protected function setSupplyPriceAttribute($value)
    {
        return bcmul($value, 100, 0);
    }

    public function getLinePriceAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }

    protected function setLinePriceAttribute($value)
    {
        return bcmul($value, 100, 0);
    }

    public function getSpecTypeTextAttribute()
    {
        $value = $this->spec_type;
        $list = $this->getSpecTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttribute()
    {
        $value = $this->status;
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getSpecTypeList()
    {
        return [1 => '单规格', 2 => '多规格'];
    }

    public function getStatusList()
    {
        return [1 => '上架', 2 => '下架'];
    }

    /**
     * 关联商品规格表
     */
    public function sku()
    {
        return $this->hasMany('App\Model\GoodsSku', 'goods_id', 'id');
    }

    /**
     * 关联商品规格关系表
     */
    public function rel()
    {
        return $this->hasMany('App\Model\GoodsSpecRel', 'goods_id', 'id');
    }

    /**
     * 关联商品规格关系表
     */
    public function goodsSpecRel()
    {
        return $this->belongsToMany('App\Model\SpecValue', 'goods_spec_rel', 'goods_id', 'value_id')->withPivot('id', 'goods_id', 'spec_id', 'value_id', 'createtime');
    }

    /**
     * 添加商品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    public function addGoodsSku(&$data, $params, $isUpdate = false)
    {
        // 更新模式: 先删除所有规格
        $model = new GoodsSku();
        $isUpdate && $model->removeAll($this['id']);
        // 添加规格数据
        if ($data['spec_type'] == 1) {
            // 单规格
            $model->sku_sn = $data['sku_sn'];
            $model->bar_code = $data['bar_code'];
            $model->sku_unique = md5($this['id'] . '_默认规格');
            $model->spec_value = '默认规格';
            $model->image = $data['image'];
            $model->supply_price = $data['supply_price'];
            $model->line_price = $data['line_price'];
            $model->weight = !empty($data['weight']) ? $data['weight'] : 0;
            $model->stock = !empty($data['stock']) ? $data['stock'] : 0;
            $this->sku()->save($model);
        } else if ($data['spec_type'] == 2) {
            $params = json_decode($params, true);
            // 添加商品与规格关系记录
            $model->addGoodsSpecRel($this['id'], $params['spec_attr']);
            // 添加商品sku
            $model->addSkuList($this['id'], $params['spec_list']);
            // 商品获取规格销售价最低的规格数据
            $skuInfo = $model->where('goods_id', $this['id'])->orderBy('supply_price', 'asc')->first();
            $this->sku_sn = $skuInfo['sku_sn'];
            $this->bar_code = $skuInfo['bar_code'];
            $this->supply_price = $skuInfo['supply_price'];
            $this->line_price = $skuInfo['line_price'];
            $this->weight = $skuInfo['weight'];
            $this->stock = $skuInfo['stock'];
            $this->save();
        }
    }

    /**
     * 获取规格信息
     */
    public function getManySpecData($spec_rel, $skuData)
    {
        // spec_attr
        $specAttrData = [];
        foreach ($spec_rel as $item) {
            if (!isset($specAttrData[$item['spec_id']])) {
                $specAttrData[$item['spec_id']] = [
                    'group_id' => $item['spec']['id'],
                    'group_name' => $item['spec']['spec_name'],
                    'spec_items' => [],
                ];
            }
            $specAttrData[$item['spec_id']]['spec_items'][] = [
                'item_id' => $item['pivot']['value_id'],
                'spec_value' => $item['spec_value'],
            ];
        }

        // spec_list
        $specListData = [];
        foreach ($skuData as $item) {
            $specListData[] = [
                'spec_id' => $item['id'],
                'sku_unique' => $item['sku_unique'],
                'value_id' => $item['value_id'],
                'rows' => [],
                'form' => [
                    'sku_sn' => $item['sku_sn'],
                    'bar_code' => $item['bar_code'],
                    'image' => $item['image'],
                    'image_url' => replace_imgs_url($item['image']),
                    'supply_price' => $item['supply_price'],
                    'line_price' => $item['line_price'],
                    'weight' => $item['weight'],
                    'stock' => $item['stock'],
                    'status' => $item['status'],
                ],
            ];
        }
        return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
    }
}
